﻿using System.Collections;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CustomControlPractice.Controls
{
    public class CustomGridView : GridView
    {
        private GridViewRow headerRow;

        [Category("Behavior")]
        [Themeable(true)]
        [Bindable(BindableSupport.No)]
        public bool AlwaysShowHeader { get; set; }

        public override GridViewRow HeaderRow
        {
            get { return base.HeaderRow ?? headerRow; }
        }

        protected override int CreateChildControls(IEnumerable dataSource, bool dataBinding)
        {
            int rowCount = base.CreateChildControls(dataSource, dataBinding);
            if (rowCount == 0 && AlwaysShowHeader)
            {
                Table childTable = CreateChildTable();
                Controls.Clear();
                Controls.Add(childTable);
                AddHeaderRow(dataSource, childTable);
            }
            return rowCount;
        }

        private void AddHeaderRow(IEnumerable dataSource, Table childTable)
        {
            DataControlField[] fields = CreateDataControlFields(dataSource);
            TableRowCollection rowCollection = childTable.Rows;

            headerRow = CreateRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal);
            InitializeRow(headerRow, fields);
            var eventArgs = new GridViewRowEventArgs(headerRow);
            OnRowCreated(eventArgs);

            rowCollection.Add(headerRow);
            headerRow.DataBind();
            OnRowDataBound(eventArgs);
        }

        private DataControlField[] CreateDataControlFields(IEnumerable dataSource)
        {
            DataControlField[] fields;
            if (AutoGenerateColumns)
            {
                var source = new PagedDataSource {DataSource = dataSource};
                ICollection autoGeneratedColumns = CreateColumns(source, true);
                fields = new DataControlField[autoGeneratedColumns.Count];
                autoGeneratedColumns.CopyTo(fields, 0);
            }
            else
            {
                fields = new DataControlField[Columns.Count];
                Columns.CopyTo(fields, 0);
            }
            return fields;
        }
    }
}
